/**
 * Created by levy on 16/7/11.
 */
import {shopping} from "../const/shopping";
import {ItemUtil} from "../components/shopping/ItemUtil";
import Fixed from "../components/Fixed";
import Item from "../components/shopping/Item";
import AddressDetail from "../components/shopping/AddressDetail";

const lf = liefeng,
    R = React,
    RC = React.createClass,
    log = lf.utils.log,
    ajax = lf.utils.ajax,
    api = shopping.api.order;


const goodsId = lf.utils.getUrlParam('goodsId'), //立即购买, 传的是goodsId
    goodsIds = lf.utils.getUrlParam('goodsIds').split(','), //购物车传的是这个参数
    isCart = goodsId ? 0 : 1;

let totalPrice = 0,
    hasCount = false,
    addressInfo; //fuck　state　的改变不会影响到didMount

/**
 * props:
 *  user
 */
const Root = RC({
    getInitialState() {
        return {
            itemList: [], //来自购物车时使用
            itemDetail: {},
            goodsIdAndNumList: [], //createOrder接口要用
            defaultAddress: '',
            updateUser: {},
            isOk: '',
        }
    },
    getDefaultAddress(user) {
        ajax({
            url: shopping.api.prefix + shopping.api.address.list,
            data: {
                custGlobalId: user.globalId|| (user.custLoginVo && user.custLoginVo.globalId),
            }
        }, null, list => {
            list.map(data => {
                if (!parseInt(data.isDefault)) return;

                this.setState({
                    defaultAddress: data,
                    isOk: true,
                });
            });

        })

    },
    goodsIdAndNumList(user){
        ajax({
            url: shopping.api.prefix + shopping.api.cart.listCartGoods,
            data: {
                custGlobalId: user.globalId  || (user.custLoginVo && user.custLoginVo.globalId),
                size: 999,
            },
            success: (data) => {
                let dataList = data.dataList,
                    itemList = [],
                    goodsIdAndNumList = this.state.goodsIdAndNumList;

                dataList.map(item => {
                    let goodsIdAndNum = {};

                    //只显示goodId属于goodsIds的商品
                    goodsIds.map(goodsId => {
                        if (item.goodsId == goodsId) {
                            itemList.push(item);

                            goodsIdAndNum.goodsId = item.goodsId;
                            goodsIdAndNum.num = item.goodsNumber;

                            goodsIdAndNumList.push(goodsIdAndNum);
                        }
                    })
                });

                this.setState({
                    itemList: itemList,
                    goodsIdAndNumList: goodsIdAndNumList
                });
            }
        });
    },
    componentWillMount() {
        let me = this,
            user = me.props.user;
        me.getDefaultAddress(user);
        if (isCart) {
            me.goodsIdAndNumList(user);
        }
        else {
            //来自立即购买
            ajax({
                url: shopping.api.prefix + shopping.api.itemDetail,
                data: {
                    goodsId: goodsId
                },
                success: (data) => {
                    this.setState({
                        itemDetail: data.data,
                        goodsIdAndNumList: [{goodsId: goodsId, num: 1}]
                    });
                }
            });
        }
        me.getDefaultAddress(user);
    },
    componentDidMount() {

        R.findDOMNode(this.refs.createOrder).addEventListener('touchend', () => {
            if (!addressInfo.id) {
                alert('请先添加收货地址');
                return;
            }

            let goodsIdAndNumList = this.state.goodsIdAndNumList;

            ajax({
                type: 'post',
                url: shopping.api.prefix + api.create,
                data: {
                    custGlobalId: this.props.user.globalId || (this.props.user.custLoginVo && this.props.user.custLoginVo.globalId),
                    goodsIdAndNum: JSON.stringify(goodsIdAndNumList),
                    mobile: this.props.user.mobile || (this.props.user.custLoginVo && this.props.user.custLoginVo.mobile),
                    isCart: isCart,
                    addressId: addressInfo.id,
                },
                success: (data) => {
                    if (data.code == 200) {
                        let goodsAmount = data.data.goodsAmount;

                        if (goodsAmount)
                            lf.appJs.doLocation(`shopping-order-pay.html?orderId=${data.data.orderId}`, '收银台');
                        else
                            lf.appJs.doLocation('shopping-order-list.html?flag=shipping', '待收货');
                    }

                    else
                        alert(data.desc);
                }
            })
        });
    },
    renderItemAndCountPrice(data, isCart) {
        let itemList = [];

        if (isCart) {
            itemList = data.map(item => {
                let salePrice = ItemUtil.getSalePrice(item, false);

                if (!hasCount) //避免refresh回来后再次计算
                    totalPrice += salePrice * 10 * 10 * item.goodsNumber;

                return <Item data={item} salePrice={salePrice}/>;
            });

            if (!hasCount) {
                totalPrice = parseInt(totalPrice);
                totalPrice = totalPrice / 100;
            }
        }
        else {
            let salePrice = ItemUtil.getSalePrice(data, false);

            //来自立即购买,数量为一个
            totalPrice = salePrice;

            itemList = <Item data={data} salePrice={salePrice} count={1}/>;
        }

        if (totalPrice)
            hasCount = true;

        return {
            itemList
        }
    },
    render() {
        let {itemList} = this.renderItemAndCountPrice(isCart ? this.state.itemList : this.state.itemDetail, isCart),
            hideCreateOrder = this.state.goodsIdAndNumList.length ? '' : 'ele-hide',
            address = this.state.defaultAddress,
            isOk = this.state.isOk;

        addressInfo = address;

        return <div className="order-confirm">
            {
                address ?
                    <div>
                        <AddressDetail data={address} addClass="border-bottom"
                                       addComponent={
                        <span className="mui-icon mui-icon-location "/>
                    }/>
                        <div className="row mui-navigate-right"
                             onTouchEnd={() => lf.appJs.doAction('shopping-address-manage.html', '管理地址')}>
                            其他收货地址
                        </div>
                    </div>
                    :
                    <div className="row mui-navigate-right"
                         onTouchEnd={() => lf.appJs.doAction('shopping-address-manage-edit.html', '新建地址')}>
                        <span className="mui-icon mui-icon-plusempty"/>
                        <span>新增收货地址</span>
                    </div>

            }
            <div className="split-line"></div>
            <p className="row border-bottom">商品信息</p>
            {itemList}
            <div className="price-info">
                <p className="row border-bottom">费用详情</p>
                <div className="row flex space-between border-bottom">
                    <span>商品金额</span>
                    <span className="red">{"￥" + (totalPrice || '0')}</span>
                </div>
            </div>
            <div className="row text-right">
                <span>实付金额</span>
                <span className="red">{"￥" + (totalPrice || '0')}</span>
            </div>
            <div className="split-line"></div>
            <Fixed data={
                    <div className={"mui-btn shopping-red-bg " + hideCreateOrder}  ref="createOrder">立即支付</div>
            }/>
        </div>
    }
});

lf.appJs.getUser(function (user) {
    R.render(<Root user={user}/>, document.getElementById('root'), function () {
    });
});